﻿Option Strict On
Option Explicit On

'Copyright (c) 2007-2010, William Severance, Jr., WESNet Designs
'All rights reserved.

'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:

'Redistributions of source code must retain the above copyright notice, this list of conditions
'and the following disclaimer.

'Redistributions in binary form must reproduce the above copyright notice, this list of conditions
'and the following disclaimer in the documentation and/or other materials provided with the distribution.

'Neither the name of William Severance, Jr. or WESNet Designs may be used to endorse or promote
'products derived from this software without specific prior written permission.

'Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
'            OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'            AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE
'            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
'            LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
'            INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
'            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
'            IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Although I will try to answer questions regarding the installation and use of this software when
'such questions are submitted via e-mail to the below address, no promise of further
'support or enhancement is made nor should be assumed.

'Developer Contact Information:
'     William Severance, Jr.
'     WESNet Designs
'     679 Upper Ridge Road
'     Bridgton, ME 04009
'     Phone: 207-647-9375
'     E-Mail: bill@wesnetdesigns.com
'     Website: www.wesnetdesigns.com

Imports DotNetNuke.Services.Exceptions

Namespace WESNet.DNN.Modules.EPrayer
    Partial Class ManageExpiredPosts
        Inherits EPrayerModuleBase

#Region "Private Members"

#End Region

#Region "Public Properties"

        Public Overrides Property PageSize() As Integer
            Get
                If divPager.Visible Then
                    Return Convert.ToInt32(ddlPageSize.SelectedValue)
                Else
                    Return MyBase.PageSize
                End If
            End Get
            Set(ByVal value As Integer)
                If divPager.Visible Then
                    Dim li As ListItem
                    li = ddlPageSize.Items.FindByValue(value.ToString)
                    If Not li Is Nothing Then
                        ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(li)
                        MyBase.PageSize = value
                    End If
                Else
                    MyBase.PageSize = value
                End If
            End Set
        End Property

        Public Property Status() As Integer
            Get
                Return Convert.ToInt32(rblStatus.SelectedValue)
            End Get
            Set(ByVal value As Integer)
                Dim li As ListItem = rblStatus.Items.FindByValue(value.ToString)
                If Not li Is Nothing Then
                    rblStatus.SelectedIndex = rblStatus.Items.IndexOf(li)
                End If
            End Set
        End Property

        Public Property CreatedBefore() As String
            Get
                Dim txtCreatedBefore As String = tbCreatedBefore.Text.Trim()
                Dim tmpDateTime As DateTime
                If txtCreatedBefore.Length > 0 Then
                    Try
                        tmpDateTime = DateTime.Parse(txtCreatedBefore)
                        Return tmpDateTime.ToShortDateString
                    Catch ex As Exception
                        '
                    End Try
                End If
                Return String.Empty
            End Get
            Set(ByVal value As String)
                Dim txtCreatedBefore As String = value.Trim()
                Dim tmpDateTime As DateTime
                If txtCreatedBefore.Length > 0 Then
                    Try
                        tmpDateTime = DateTime.Parse(txtCreatedBefore)
                        tbCreatedBefore.Text = tmpDateTime.ToShortDateString
                    Catch ex As Exception
                        tbCreatedBefore.Text = String.Empty
                    End Try
                Else
                    tbCreatedBefore.Text = String.Empty
                End If
            End Set
        End Property
#End Region

#Region "Private Properties"
        Private ReadOnly Property Filter() As String
            Get
                Dim sb As New StringBuilder

                If Status <> -1 Then
                    sb.AppendFormat("(R.StatusID = {0})", Status)

                    If CreatedBefore <> String.Empty Then
                        sb.Append(" AND ")
                        sb.AppendFormat("(CreatedDate < convert(char(23), '{0}',126))", CreatedBefore)
                    End If
                End If
                Return sb.ToString
            End Get
        End Property
#End Region

#Region "Event Handlers"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsAdministrator Then Response.Redirect(AccessDeniedURL(), True)

            rblStatus.Attributes.Add("onclick", "javascript:statusChanged(this);")

            btnSelectAll.OnClientClick = "javascript:return setAllSelected('" & gvExpiredPosts.ClientID & "', true);"
            btnClearSelected.OnClientClick = "javascript:return setAllSelected('" & gvExpiredPosts.ClientID & "', false);"
            DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(btnRemoveSelected, Localize("Confirm_Removal_All"))

            If Not String.IsNullOrEmpty(Request.QueryString("currentpage")) Then
                CurrentPage = Convert.ToInt32(Request.QueryString("currentpage"))
            Else
                CurrentPage = 1
            End If

            Dim RequestedPageSize As Integer
            If Not String.IsNullOrEmpty(Request.QueryString("pagesize")) Then
                RequestedPageSize = Convert.ToInt32(Request.QueryString("pagesize"))
            Else
                RequestedPageSize = UserInfo.PageSize
            End If

            If Not IsPostBack Then
                PopulatePageSizes(ddlPageSize, RequestedPageSize)
                PageSize = RequestedPageSize
            Else
                If PageSize = -1 Then PageSize = RequestedPageSize
            End If

            With ctlPager
                .PageSize = RequestedPageSize
                .CurrentPage = CurrentPage
                .TabID = TabId
            End With

            lnkCreatedBefore.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(tbCreatedBefore)

            If Not IsPostBack Then
                PopulateFilter()
                If Not String.IsNullOrEmpty(Request.QueryString("status")) Then
                    Status = Convert.ToInt32(Request.QueryString("status"))
                Else
                    Status = -1
                End If
                If Not String.IsNullOrEmpty(Request.QueryString("createdbefore")) Then CreatedBefore = Request.QueryString("createdbefore")
                Utilities.LocalizeGridView(gvExpiredPosts, LocalResourceFile)
                BindGrid()
            End If
            If Status = -1 Then
                divCreatedBefore.Style.Add("visibility", "hidden")
            Else
                divCreatedBefore.Style.Add("visibility", "visible")
            End If
        End Sub

        Protected Sub btnCommandHandler(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemoveSelected.Click, btnSelectAll.Click, btnClearSelected.Click
            Select Case CType(sender, LinkButton).CommandName
                Case "SelectAll"
                    SetAllSelected(True)
                Case "ClearSelected"
                    SetAllSelected(False)
                Case "RemoveSelected"
                    Dim epc As New EPrayerController
                    For Each row As GridViewRow In gvExpiredPosts.Rows
                        If row.RowType = DataControlRowType.DataRow Then
                            Dim cbSelcted As CheckBox = CType(row.FindControl("cbSelected"), CheckBox)
                            If cbSelcted.Checked Then
                                Dim PostID As Integer = Convert.ToInt32(gvExpiredPosts.DataKeys(row.DataItemIndex).Value)
                                If PostID <> -1 Then
                                    epc.DeletePost(PostID)
                                End If
                            End If
                        End If
                    Next
                    BindGrid()
            End Select
        End Sub

        Protected Sub gvExpiredPosts_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvExpiredPosts.RowCommand
            If e.CommandName = "Remove" Then
                Dim PostID As Integer = Convert.ToInt32(e.CommandArgument)
                If PostID <> -1 Then
                    Dim epc As New EPrayerController
                    epc.DeletePost(PostID)
                End If
                BindGrid()
            End If
        End Sub

        Protected Sub gvExpiredPosts_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvExpiredPosts.RowCreated
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim cmdRemove As ImageButton = CType(e.Row.FindControl("cmdRemove"), ImageButton)
                If Not cmdRemove Is Nothing Then
                    cmdRemove.OnClientClick = "javascript:return confirmRemoval();"
                End If
            End If
        End Sub

        Protected Sub cmdReturn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdReturn.Click
            Try
                Response.Redirect(ReturnUrl, True)
            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Protected Sub ddlPageSize_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlPageSize.SelectedIndexChanged
            CurrentPage = 1 'reset to first page when filter is applied
            Response.Redirect(EditUrl("", "", "mngexp", GetQueryStringParams()), True)
        End Sub

        Protected Sub lnkApply_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkApply.Click
            CurrentPage = 1 'reset to first page when filter is applied
            Response.Redirect(EditUrl("", "", "mngexp", GetQueryStringParams()), True)
        End Sub

#End Region

#Region "Private Methods"

        Private Sub PopulateFilter()
            Dim epc As New EPrayerController
            With rblStatus
                .DataSource = epc.GetStati()
                .DataBind()
                .Items.Insert(0, New ListItem(Localize("Expired.Text"), "-1"))
            End With
        End Sub

        Private Sub BindGrid()
            Dim TotalRecords As Integer
      Dim objRequests As List(Of RequestInfo)

            Dim epc As New EPrayerController
            If Status = -1 Then
                objRequests = epc.GetExpiredRequests(ModuleId, Filter, "Order_Date_ASC", UserId, PageSize, CurrentPage - 1, TotalRecords)
            Else
                objRequests = epc.GetRequests(ModuleId, &HFFFF, Filter, True, "Order_Date_ASC", UserId, PageSize, CurrentPage - 1, TotalRecords)
            End If
            If objRequests.Count > 0 Then
                gvExpiredPosts.DataSource = objRequests
                gvExpiredPosts.DataBind()
                With ctlPager
                    .TotalRecords = TotalRecords
                    .QuerystringParams = "&ctl=mngexp&mid=" & ModuleId.ToString & GetQueryStringParams()
                End With
                divResults.Visible = True
                lblError.Visible = False
                lblError.Text = String.Empty
                ctlPager.Visible = PageSize <> 0 And TotalRecords > PageSize
            Else
                divResults.Visible = False
                lblError.Visible = True
                lblError.Text = Localize("No_Posts_Found")
            End If
        End Sub

        Protected Function GetNavigationParams() As String()
            Dim params As New ArrayList
            Dim result As String()
            If PageSize <> UserInfo.PageSize Then params.Add("pagesize=" & PageSize.ToString)
            If CurrentPage <> 1 Then params.Add("currentpage=" & CurrentPage.ToString)
            If Status <> -1 Then params.Add("status=" & Status.ToString)
            If CreatedBefore <> String.Empty Then params.Add("createdbefore=" & Server.UrlEncode(CreatedBefore))
            result = CType(params.ToArray(GetType(String)), String())
            Return result
        End Function

        Protected Function GetQueryStringParams() As String
            Dim sb As New StringBuilder
            Dim params As String() = GetNavigationParams()
            For Each s As String In params
                If Not s.StartsWith("currentpage") Then
                    sb.Append("&")
                    sb.Append(s)
                End If
            Next
            Return sb.ToString
        End Function

        Private Sub SetAllSelected(ByVal Selected As Boolean)
            For Each row As GridViewRow In gvExpiredPosts.Rows
                If row.RowType = DataControlRowType.DataRow Then
                    Dim cbSelcted As CheckBox = CType(row.FindControl("cbSelected"), CheckBox)
                    cbSelcted.Checked = Selected
                End If
            Next
        End Sub
#End Region

        Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            Dim sb As New StringBuilder
            sb.AppendLine("function confirmRemoval() {")
            sb.Append("    var s = '")
            sb.Append(Localize("Confirm_Removal"))
            sb.AppendLine("';")
            sb.AppendLine("    return confirm(s);")
            sb.AppendLine("}")
            sb.AppendLine()
            sb.AppendLine("function statusChanged(sender) {")
            sb.Append("    var divCreatedBefore = document.getElementById('")
            sb.Append(divCreatedBefore.ClientID)
            sb.AppendLine("');")
            sb.AppendLine("    var visibility = 'visible';")
            sb.AppendLine("    var rbtns = sender.getElementsByTagName('input');")
            sb.AppendLine("    for (var i=0; i<rbtns.length; i++) {")
            sb.AppendLine("       var rbtn = rbtns[i];")
            sb.AppendLine("       if (rbtn.type == 'radio' && rbtn.id.indexOf('rblStatus',0) >= 0) {")
            sb.AppendLine("            if (rbtn.value == '-1' && rbtn.checked) visibility='hidden';")
            sb.AppendLine("       }")
            sb.AppendLine("    }")
            sb.AppendLine("    if (divCreatedBefore) {")
            sb.AppendLine("         divCreatedBefore.style.visibility = visibility;")
            sb.AppendLine("    }")
            sb.AppendLine("}")
            sb.AppendLine()
            sb.AppendLine("function setAllSelected(gvCtrlID, selected) {")
            sb.AppendLine("    var gvCtrl = document.getElementById(gvCtrlID);")
            sb.AppendLine("    if (gvCtrl) {")
            sb.AppendLine("         var cbs = gvCtrl.getElementsByTagName('input');")
            sb.AppendLine("         for (var i=0; i<cbs.length; i++) {")
            sb.AppendLine("            var cb = cbs[i];")
            sb.AppendLine("            if (cb.type == 'checkbox' && cb.id.indexOf('cbSelected',0) >= 0) {")
            sb.AppendLine("               cb.checked = selected;")
            sb.AppendLine("            }")
            sb.AppendLine("         }")
            sb.AppendLine("         return false;")
            sb.AppendLine("   }")
            sb.AppendLine("   return true;")
            sb.AppendLine("}")

            If Not Page.ClientScript.IsClientScriptBlockRegistered(Me.GetType, "EPrayer_MngExp") Then
                Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "EPrayer_MngExp", sb.ToString, True)
            End If

        End Sub
    End Class
End Namespace
